package com.tao.config.shiro;

import com.tao.pojo.User;
import com.tao.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;

    //    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登陆对象
        Subject subject=SecurityUtils.getSubject();


        User currentUser = (User) subject.getPrincipal();//取出下面获得的值
        //设下权限赋值

        //每个数据 自己带着的权限
//        System.out.println("判断授权名称："+currentUser.getPerms());

        if (currentUser.getPerms().equals("root")){
            info.addStringPermission(currentUser.getPerms());
            System.out.println("授权权限："+currentUser.getPerms());
            info.addRole("root");
        }

        return info;
    }

    //    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        System.out.println("执行了认证");
        //上面参数的token
        UsernamePasswordToken usertoken= (UsernamePasswordToken)token;

////伪造数据
//        String name="root";
//        String password="abc123";
//// 账户认证
//        if (!usertoken.getUsername().equals(name) ){
////            return null 会抛出异常 用户名错误
//            return null;
//        }

//        连接真实数据库
        User user = userService.selectByname(usertoken.getUsername());
        if (user==null){ //查不出来
            return null;
        }

        System.out.println(user.getUsername()+"用户名密码正确，登陆成功");
        String password=user.getPassword();
        //密码认证  shiro 自动做    第一个参数让上面的授权拿到
        return new SimpleAuthenticationInfo(user,password,this.getName());
    }
}
